import { createRouter, createWebHistory } from "vue-router";
import Api from "../api";
import routes from "./staticRouter";
import { ref } from 'vue'
const router = createRouter({
    history: createWebHistory(),
    routes
})
router.beforeEach(async (to, from, next) => {
    if (localStorage.getItem('token') !== null) {
        if (registerFresh.value) {
            let { data } = await Api.Menu.list();
            let routerList = generateRouter(data.data)
            routerList.map(item => {
                router.options.routes[3].children.push(item.chidlren[0])
            })
            console.log(router.options.routes[3]);
            router.addRoute(router.options.routes[3])
            registerFresh.value = false;
            next({ path: `${to.path}` });
        } else {
            router.addRoute(router.options.routes[3])
            next();
        }
    } else {
        next()
    }
})
const registerFresh = ref(true)
function generateRouter(RouterList) {
    let newRoutes;
    newRoutes = RouterList.map(r => {
        let route;
        if (r.type === 0) {
            route = {
                name: r.menu_module,
                meta: JSON.parse(r.meta),
            }
        }
        if(r.type === 1) {
            route = {
                path: r.path,
                name: r.menu_module,
                meta: JSON.parse(r.meta),
                component: () => import(`../view/${r.menu_module}.vue`)
            }
        }
        if (r['children'].length > 0) {
            route.chidlren = generateRouter(r["children"])
        }
        return route
    })
    return newRoutes
}
export default router;